package com.technology.education.ui.common.information

import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.lifecycle.lifecycleScope
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.technology.education.R
import com.technology.education.databinding.ActivityCompleteInfoBinding
import me.hgj.jetpackmvvm.base.activity.BaseVmDbActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.technology.education.data.AppData
import com.technology.education.data.SpKeys
import com.technology.education.data.model.ProvinceModel
import com.technology.education.ext.*
import com.technology.education.ui.student.MainStudentActivity
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.util.startActivity


/**
 * 完善个人信息
 */
class CompleteInfoActivity :
    BaseVmDbActivity<CompleteInfoViewModel, ActivityCompleteInfoBinding>() {
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        mDatabind.click = ClickProxy()
        mDatabind.tvLogin.text = getMiddleColor("已有账号？立即去", "登录", "", getColor(R.color.theme_color))
        lifecycleScope.launch {
            initJsonData()
        }
    }

    private var options1Items: List<String> = ArrayList()
    private val options2Items: ArrayList<ArrayList<String>> = ArrayList()
    private val options3Items: ArrayList<ArrayList<ArrayList<String>>> = ArrayList()

    private fun initJsonData() { //解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         */
        val jsonData: String =
            getJson("province.json") //获取assets目录下的json文件数据
        val jsonBean: ArrayList<ProvinceModel> = Gson().fromJson(
            jsonData,
            object : TypeToken<ArrayList<ProvinceModel>>() {}.type
        ) //用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */

        options1Items = jsonBean.map {
            it.name ?: ""
        }
        jsonBean.forEach {
            options2Items.add(it.city!!.map { city ->
                city.name ?: ""
            } as java.util.ArrayList<String>)
            val area: ArrayList<ArrayList<String>> = ArrayList()
            it.city!!.forEach { city ->
                city.area?.let { it1 -> area.add(it1 as java.util.ArrayList<String>) }
            }
            options3Items.add(area)
        }

    }


    private var picker: OptionsPickerView<String>? = null
    private fun showPicker() {
        if (picker == null) {
            picker = OptionsPickerBuilder(
                this
            ) { options1, options2, options3, v ->
                mViewModel.province = options1Items[options1]
                mViewModel.city = options2Items[options1][options2]
                mViewModel.district = options3Items[options1][options2][options3]
                mViewModel.address.set("${mViewModel.province} ${mViewModel.city} ${mViewModel.district}")
            }.setTitleText("选择所在城市")
                .setTitleSize(16)
                .setContentTextSize(14)
                .build()
            picker!!.setPicker(
                options1Items,
                options2Items as List<List<String>>, options3Items as List<List<List<String>>>
            )
        }
        picker!!.show()
    }

    override fun showLoading(message: String) {
    }

    override fun dismissLoading() {
    }

    override fun createObserver() {
        mViewModel.result.observe(this) {
            if (it) {
                if (AppData.MEMBER_TYPE == "0") {
                    //学生无需完善支付信息
                    saveData(SpKeys.IS_LOGIN, true)
                    getAppViewModel().getInfo()
                    startActivity(MainStudentActivity::class)
                } else {
                    startActivity(CompleteWithdrawActivity::class,Pair("type",0))
                }

            }
        }
    }

    inner class ClickProxy {
        fun goLogin() {
            onBackPressed()
        }

        fun show() {
            closeInput()
            showPicker()
        }
    }

    fun closeInput() {
        val inputMethodManager =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (inputMethodManager != null && currentFocus != null) {
            inputMethodManager.hideSoftInputFromWindow(
                currentFocus
                !!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }
}